package com.liyao.storehouse.api.base;

import cn.hutool.json.JSONObject;
import com.liyao.storehouse.api.entity.ClientCallLog;
import com.liyao.storehouse.api.service.IClientCallLogService;
import com.liyao.storehouse.api.utill.DateFormatUtils;
import com.liyao.storehouse.api.utill.RSAUtils;
import com.liyao.storehouse.api.utill.SystemConfig;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class ThirdPartyCallBaseController<T> {

    @Resource
    protected RSAUtils rsa;
    @Resource
    private IClientCallLogService clientCallLogService;

    /**
     * 验证token有效性
     */
    public JSONObject verificationToken(HttpServletRequest request) {
        JSONObject data = new JSONObject();

        String token = request.getHeader("X-Api-Token");

        if (!StringUtils.hasLength(token)) {
            data.putOpt("errcode", "1001");
            data.putOpt("errmsg", "请求头缺失");
            return data;
        }

        String decryptStr = "";
        try {
            decryptStr = rsa.decrypt(token, SystemConfig.RSA_PRIVATE_KEY);
        } catch (Exception e) {
            data.putOpt("errcode", "1005");
            data.putOpt("errmsg", "无效token");
            return data;
        }

        long timestamp = Long.parseLong(decryptStr.split("#")[1]);
        long now = new Date().getTime() / 1000;
        if ((now - timestamp) > 7200) {
            data.putOpt("errcode", "1006");
            data.putOpt("errmsg", "token已过期");
            return data;
        }

        String clientId = decryptStr.split("#")[0];
        data.putOpt("errcode", "0");
        data.putOpt("errmsg", clientId);
        return data;
    }

    /**
     * 验证token有效性
     * @param body 参数
     * @param page 是否分页
     * @param params 非分页参数，必传参数: param1,param2,param3
     * @return JSONObject
     */
    public JSONObject verificationParamsPage(JSONObject body, boolean page, String params) {
        JSONObject data = new JSONObject();

        if (page && (!body.containsKey("pageNum") || !body.containsKey("pageSize"))) {
            data.putOpt("errcode", "1002");
            data.putOpt("errmsg", "参数缺失: pageNum,pageSize必传");
            return data;
        }

        if (body.containsKey("pageNum")) {
            int num = 0;
            try {
                num = Integer.parseInt(body.getStr("pageNum"));
            } catch (Exception e) {
                data.putOpt("errcode", "1007");
                data.putOpt("errmsg", "参数不符合");
                return data;
            }
            if (num < 1) {
                data.putOpt("errcode", "1007");
                data.putOpt("errmsg", "参数不符合");
                return data;
            }
        }

        if (body.containsKey("pageSize")) {
            int size = 0;
            try {
                size = Integer.parseInt(body.getStr("pageSize"));
            } catch (Exception e) {
                data.putOpt("errcode", "1007");
                data.putOpt("errmsg", "参数不符合");
                return data;
            }
            if (size < 1) {
                data.putOpt("errcode", "1007");
                data.putOpt("errmsg", "参数不符合");
                return data;
            }
            if (size > 5000) {
                data.putOpt("errcode", "1008");
                data.putOpt("errmsg", "分页查询数据量超出最大限制");
                return data;
            }
        }

        if (StringUtils.hasLength(params)) {
            for (String param : params.split(",")) {
                if (!body.containsKey(param)) {
                    data.putOpt("errcode", "1002");
                    data.putOpt("errmsg", "参数缺失: " + param + "必传");
                    return data;
                }
            }
        }

        data.putOpt("errcode", "0");
        data.putOpt("errmsg", "校验通过");
        return data;
    }

    /**
     * 添加第三方系统调用日志
     * @param body 请求体
     * @param request 请求
     */
    public void saveClientCallLog(JSONObject body, HttpServletRequest request) {
        String clientId = rsa.decrypt(request.getHeader("X-Api-Token"), SystemConfig.RSA_PRIVATE_KEY).split("#")[0];
        ClientCallLog log = new ClientCallLog();
        log.setClientId(clientId);
        log.setTime(DateFormatUtils.dayAndTime());
        log.setApiName(request.getRequestURI());
        log.setParams(body.toString());
        clientCallLogService.insertAPILog(log);
    }
}
